import React, { useState, useEffect } from 'react'
import { Select, Input, Button, Form, Modal, InputNumber, Radio, DatePicker, message } from 'antd'
import UploadImg from '../../../components/UploadImg'
import api from '../../../api/activityManage'

import moment from 'moment';

const { Option } = Select

let timeout;
let currentValue;
function fetch(value,projectTypeId, callback){
	if (timeout) {
		clearTimeout(timeout);
		timeout = null;
	}
	currentValue = value;

	function fake() {
		api.getTeachPlan({projectTypeId:projectTypeId,name:value/* ,startRows:1,pageSize:100 */},(res)=>{
			if (currentValue === value) {
				callback(res.recordList);
			}
		})
	}

	timeout = setTimeout(fake, 300);
}
const EditClassModal = ({actId,editModal,showModal,form}) => {
    const [state, setState] = useState({
		projectTypeArr:[],//项目类型数组
		teachPlanArr:[],//教学计划数组
		btnLoading:false,//按钮loading
		fileList:[//格式：{uid: '-1',name: 'image.png',status: 'done',url:''}
			[],//classUrl
			[],//classInfoUrl
			[],//classPoster
		],
	});

    //更新state
    const updateState = (newState) => {
        let data = JSON.parse(JSON.stringify(state))
        setState(Object.assign({}, data, newState))
	}
	//显示的时候初始化
	useEffect(()=>{
		if(editModal.visible){
			// 初始化图片
			let fileList = editModal.data.id?[
				[{uid: '-1',status: 'done',url:editModal.data.classUrl}],
				[{uid: '-1',status: 'done',url:editModal.data.classInfoUrl}],
				[{uid: '-1',status: 'done',url:editModal.data.classPoster}],
			]:[[],[],[]]
			//获取教学计划
            let getTeachPlan = new Promise((resolve, reject) => {
				if(editModal.data.id){//编辑
					let obj = {
						projectTypeId:editModal.data.projectTypeId,
						// name:editModal.data.projectTypeName,
						// startRows:1,
						// pageSize:100
					}
					api.getTeachPlan(obj,(res)=>{
						if(res){
							resolve(res.recordList)
						}else{
							resolve([])
						}
					})
				}else{
					resolve([])
				}
            })
            //获取项目类型
            let getProjectType = new Promise((resolve, reject) => {
				if(state.projectTypeArr.length==0){
					api.getProjectType({status:1},(res)=>{
						if(res){
							resolve(res)
						}else{
							resolve([])
						}
					})
				}else{
					resolve(state.projectTypeArr)
				}
            })
            Promise.all([getTeachPlan,getProjectType]).then((res) => {
                updateState({
					teachPlanArr:res[0],
					projectTypeArr:res[1],
					fileList:fileList
                })
            }).catch((error) => {
                console.log(333,error)
            })
		}
	},[editModal.visible])
    // 监听图片文件
    const onChangeImg_1 = (fileList) => {
		console.log(fileList)
		let arr = JSON.parse(JSON.stringify(state.fileList))
		arr[0] = fileList
		updateState({
			fileList:arr,
			classUrl:fileList.length > 0 ? fileList[0].url : ""
		})
		//设置表单值
		form.setFieldsValue({
			classUrl: fileList.length > 0 ? fileList[0].url : "",
		});
	}
    const onChangeImg_2 = (fileList) => {
		console.log(fileList)
		let arr = JSON.parse(JSON.stringify(state.fileList))
		arr[1] = fileList
		updateState({
			fileList:arr,
			classInfoUrl:fileList.length > 0 ? fileList[0].url : ""
		})
		//设置表单值
		form.setFieldsValue({
			classInfoUrl: fileList.length > 0 ? fileList[0].url : "",
		});
	}
    const onChangeImg_3 = (fileList) => {
		console.log(fileList)
		let arr = JSON.parse(JSON.stringify(state.fileList))
		arr[2] = fileList
		updateState({
			fileList:arr,
			classPoster:fileList.length > 0 ? fileList[0].url : ""
		})
		//设置表单值
		form.setFieldsValue({
			classPoster: fileList.length > 0 ? fileList[0].url : "",
		});
	}
	// 改变项目类型
	const handleChange = (value) => {
		form.resetFields('teachId')
		form.setFieldsValue({
			teachId: undefined,
		});
		api.getTeachPlan({projectTypeId:value},(res)=>{
			updateState({
				teachPlanArr:res.recordList
			})
		})
	};
	// 搜索教学计划
	const handleSearch = (value)=>{
		fetch(value,form.getFieldValue('projectTypeId'), data => updateState({teachPlanArr:data}));
	}
	//禁选日期
	const disabledDate =(current)=> {
		// return current && current < moment().endOf('day');
	}
	//提交
    const handleSubmit = (e) => {
        e.preventDefault();
        form.validateFields((err, values) => {
			if (!err) {
				updateState({btnLoading:true})
				let obj = Object.assign({},{actId:actId},values)
				obj.endTime = moment(values.endTime).format('YYYY-MM-DD HH:mm:ss')
				if(editModal.data.id){//编辑
					obj.id = editModal.data.id
				}
				api.addActivitiesClass(obj,(res)=>{
					if(res){
						closeModal(4,{})
						message.success(obj.id?'编辑成功':'新建成功')
					}
					updateState({btnLoading:false})
				})
            }
        });
    }
    //关闭模态框
    const closeModal = (type)=>{
		showModal(type,{})
		form.resetFields()
		updateState({fileList:[[],[],[]]})
	}
	
    const { getFieldDecorator } = form;
    return (
            <Modal title={editModal.title}
				visible={editModal.visible}
				footer={null}
				onCancel={()=>{closeModal(3)}}
				width={600}
			>
                <Form labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} onSubmit={handleSubmit} style={{height:650,overflowY:'scroll'}}>
					<Form.Item label="课程名称">
						{getFieldDecorator('name', {
							initialValue:editModal.data.name,
							rules: [{ required: true, message: '请输入课程名称' }],
						})(
							<Input style={{ width: 300 }} maxLength={15} />,
						)}
					</Form.Item>
					<Form.Item label="课程封面">
						{getFieldDecorator('classUrl', {
							initialValue:editModal.data.classUrl,
							rules: [{required: true,message: '请上传课程封面',},]
						})(
							<UploadImg onChangeImg={onChangeImg_1} fileList={state.fileList[0]} />
						)}
					</Form.Item>
					<Form.Item label="课程详情">
						{getFieldDecorator('classInfoUrl', {
							initialValue:editModal.data.classInfoUrl,
							rules: [{required: true,message: '请上传课程详情',},]
						})(
							<UploadImg onChangeImg={onChangeImg_2} fileList={state.fileList[1]} />
						)}
					</Form.Item>
					<Form.Item label="课程海报">
						{getFieldDecorator('classPoster', {
							initialValue:editModal.data.classPoster,
							rules: [{required: true,message: '请上传课程海报',},]
						})(
							<UploadImg onChangeImg={onChangeImg_3} fileList={state.fileList[2]} />
						)}
					</Form.Item>
					<Form.Item label="课程描述">
						{getFieldDecorator('memo', {
							initialValue:editModal.data.memo,
							rules: [{ required: true, message: '请输入课程描述' }],
						})(
							<Input style={{ width: 300 }} maxLength={30} />,
						)}
					</Form.Item>
					<Form.Item label="课程原价">
						{getFieldDecorator('price', {
							initialValue:editModal.data.price,
							rules: [{ required: true, message: '请输入课程原价' }],
						})(
							<InputNumber style={{ width: 300 }} max={99999} min={0} precision={2} />
						)}
					</Form.Item>
					<Form.Item label="项目类型">
						{getFieldDecorator('projectTypeId', {
							initialValue:editModal.data.projectTypeId,
							rules: [{ required: true, message: '请选择项目类型' }],
						})(
							<Select style={{ width: 300 }}
								showSearch
								optionFilterProp="children"
								onChange={handleChange}
								filterOption={(input, option) =>
									option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
								}
							>
								{state.projectTypeArr.map((v,i)=>{
									return (
										<Option key={i} value={v.id}>{v.name}</Option>
									)
								})}
							</Select>
						)}
					</Form.Item>
					<Form.Item label="关联公众号">
						{getFieldDecorator('wxAccount', {
							initialValue:editModal.data.wxAccount,
							rules: [{ required: true, message: '请输入关联公众号' }],
						})(
							<Input style={{ width: 300 }} maxLength={20} />,
						)}
					</Form.Item>
					<Form.Item label="公众号链接">
						{getFieldDecorator('wxLink', {
							initialValue:editModal.data.wxLink,
							rules: [{ required: true, message: '请输入公众号链接' }],
						})(
							<Input style={{ width: 300 }} maxLength={100} />,
						)}
					</Form.Item>
					<Form.Item label="对应教学计划">
						{getFieldDecorator('teachId', {
							initialValue:editModal.data.teachId,
							rules: [{ required: true, message: '请选择对应教学计划' }],
						})(
							<Select style={{ width: 300 }}
								disabled={!form.getFieldValue('projectTypeId')}
								showSearch
								showArrow={false}
								filterOption={false}
								onSearch={handleSearch}
								placeholder="请先选择项目类型，再输入关键字进行搜索"
								notFoundContent="请输入关键字进行搜索"
							>
								{state.teachPlanArr.map((v,i)=>{
									return (
										<Option key={i} value={v.id}>{v.name}</Option>
									)
								})}
							</Select>
						)}
					</Form.Item>
					<Form.Item label="课程有效期">
						{getFieldDecorator('endTime', {
							initialValue:editModal.data.endTime?moment(editModal.data.endTime,'YYYY-MM-DD HH:mm:ss'):null,
							rules: [{ required: true, message: '请选择课程有效期' }],
						})(
							<DatePicker disabledDate={disabledDate} format="YYYY-MM-DD HH:mm:ss" showTime={true} />,
						)}
					</Form.Item>
					<Form.Item label="权重">
						{getFieldDecorator('weight', {
							initialValue:editModal.data.weight,
							rules: [{ required: true, message: '请输入权重' }],
						})(
							<InputNumber style={{ width: 200 }} max={999} min={1} precision={0} />
						)}
					</Form.Item>
					<Form.Item label="状态">
						{getFieldDecorator('state', {
							initialValue:editModal.data.state,
							rules: [{ required: true, message: '请选择状态' }],
						})(
							<Radio.Group>
								<Radio value={1}>有效</Radio>
								<Radio value={0}>无效</Radio>
							</Radio.Group>
						)}
					</Form.Item>
					<Form.Item wrapperCol={{ span: 24 }} style={{textAlign:'right'}}>
						<Button onClick={()=>{closeModal(3)}}>取消</Button>
						<Button style={{marginLeft:30}} type="primary" htmlType="submit" loading={state.btnLoading}>保存</Button>
					</Form.Item>
                </Form>
            </Modal>
    )
}

export default Form.create({})(EditClassModal)